import { useState } from 'react';
import Taro, { useLoad } from '@tarojs/taro';
import { View, Text, Image } from '@tarojs/components';
import { AtButton, AtCheckbox } from 'taro-ui';
import IconFont from '@/assets/Iconfont';
import Navigation from '@/components/Navigation';
import PhoneLogin from './components/PhoneLogin';
import { getAuthCode, setAuthCode } from '@/base/auth/authCode';
import { syncLocation, wxLogin } from '@/business/services/user/login/login';
import { cityTreeListStore } from '@/business/store/city/city';
import cssModule from './index.module.scss';
import { initUser } from '@/business/services/im';

/**
 * @description 登录
 * author Shawn
 */

export default function Login() {
  useLoad(() => {
    console.log('Page loaded.');
  });

  const [showPhoneLogin, setShowPhoneLogin] = useState(false);
  const [agreementChecked, setAgreementChecked] = useState<string[]>([]);

  // 获取城市数据
  const getCityTreeList = async () => {
    await cityTreeListStore.getState().getCityTreeList();
  }

  // 设置当前城市
  const setLocation = async () => {
    const res = await Taro.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
    });
    const { latitude, longitude } = res;

    if (latitude && longitude) {
      await syncLocation({ latitude, longitude })
    }
  }


  // 微信授权登录
  const setUserAuthCode = async () => {
    if (!agreementChecked.length) {
      Taro.showToast({
        title: '请同意用户协议和隐私政策',
        icon: 'none'
      })
      return
    }
    await setAuthCode();
    const authCode = await getAuthCode();
    const res = await wxLogin({
      code: authCode,
    });
    Taro.setStorageSync('openToken', res.data.token);
    Taro.setStorageSync('userId', res.data.userId);
    Taro.setStorageSync('openid', res.data.openid);

    if (Taro.getStorageSync('openToken')) {
      getCityTreeList()
    }
    await setLocation()
    const userSig = Taro.getStorageSync('imUserSig');
    if (!userSig) {
      const imRes = await initUser({})
      Taro.setStorageSync('imUserSig', imRes.data.imUserId);
    }
    Taro.setStorageSync('isLogin', true);
    // 没注册过
    if (!res.data.registered) {
      Taro.redirectTo({
        url: `/pages/register/index?openid=${res.data.openid}`,
      });
    } else if (res.data.firstLogin) {
      Taro.redirectTo({
        url: `/subPackages/person/index`,
      });
    } else {
      Taro.reLaunch({
        url: `/pages/index/index`,
      });
    }
  };

  // 去注册
  const handleGoRegister = () => {
    Taro.navigateTo({
      url: '/pages/register/index',
    });
  };

  const onAgreement = () => {
    Taro.navigateTo({
      url: '/subPackages/agreement/index'
    })
  }

  const onprivacyPolicy = () => {
    Taro.navigateTo({
      url: '/subPackages/privacyPolicy/index'
    })
  }

  return (
    <View>
      {/* 自定义导航栏 */}
      <Navigation />

      {/* 页面内容 */}
      <View className={cssModule.container}>
        <View className={cssModule.logo}>
          <View className={cssModule.logoImage}>
            <Image src='https://baoyouqun.cn/files/2025/11/09/91c8ae6d-4e5c-4216-a064-a702d4a1eedc.jpg' mode='aspectFill' />
          </View>
          <Text className={cssModule.logoDesc}>找资源？进豹友群！</Text>
        </View>
        <View className={cssModule.wechatLogin}>
          {!showPhoneLogin && (
            <AtButton type='primary' onClick={setUserAuthCode}>
              <View className={cssModule.wechatLoginContent}>
                <IconFont name='wechat' size={36} />
                <Text className='ml-2'>微信授权快捷登录</Text>
              </View>
            </AtButton>
          )}
        </View>
        <View className={cssModule.accountLogin}>
          {!showPhoneLogin ? (
            <AtButton type='secondary' onClick={() => setShowPhoneLogin(true)}>
              <View className={cssModule.accountLoginContent}>
                <Text className='ml-2'>手机号登录</Text>
              </View>
            </AtButton>
          ) : (
            <PhoneLogin agreementChecked={agreementChecked} />
          )}
        </View>
        <View className={cssModule.agreement}>
          <View className={cssModule.checkboxContainer}>
            <AtCheckbox
              options={[{ label: '', value: 'agree' }]}
              selectedList={agreementChecked}
              onChange={(value) => setAgreementChecked(value)}
            />
            <Text>已经阅读并同意</Text>
            <Text className='text-[#6190e8]' onClick={onAgreement}>《用户协议》</Text>
            <Text>和</Text>
            <Text className='text-[#6190e8]' onClick={onprivacyPolicy}>《隐私政策》</Text>
          </View>
        </View>
      </View>
      <View className={cssModule.euity} onClick={handleGoRegister}>
        <Text>注册新用户</Text>
      </View>
    </View>
  );
}
